//
//  StatuesDataManager.swift
//  DSWeiBo
//
//  Created by 刘星 on 16/8/11.
//  Copyright © 2016年 LiuXing. All rights reserved.
//

import UIKit

class StatuesDataManager: NSObject {
    class  func loadStatuses() {
        // 1.从本地数据库中获取
        // 2.如果本地有, 直接返回
        // 3.从网络获取
        // 4.将从网络获取的数据缓存起来
    }
    /// 缓存微博数据
    class func cacheStatuses(statues: [[String: AnyObject]]) {
        //  准备数据
        let userId = UserAccountViewModel.shareIntance.account?.uid
        // 定义SQL语句
        let sql = "INSERT INTO T_Status" +
            "(statusId, statusText, userId)" +
            "VALUES" +
        "(?, ?, ?);"
        // 执行SQL语句
        SQLiteManager.shareManager().dbQueue?.inTransaction({ (db, rollback) in
            for dict in statues {
                // id
                let statusId = dict["id"]!
                // JSON -> 二进制 -> 字符串
                guard let data = try? NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted) else {
                    return
                }
                let statusText = String(data: data, encoding: NSUTF8StringEncoding)!
//                print(statusText)
                if db!.executeUpdate(sql, withArgumentsInArray: [statusId, statusText, userId!]) {
                    // 如果插入数据失败, 就回滚
                    rollback.memory = true
                }
            }
        })
    }
}
